<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog ref="editDialog" v-model="openFlag" title="添加入库单" width="50%" append-to-body>
      <div>
        <div class="dialog-content">
          <div class="dialog-main">
            <h3 style="color:black;">基本信息</h3>
            <div class="block" style="display: flex; align-items: center;">
              <span class="demonstration" style="margin-right: 8px; color: '#606266';">入库处理时间</span>
              <el-date-picker v-model="value2" type="datetime" placeholder="入库处理时间" align="right"
                :picker-options="pickerOptions" style="width: 30%;" :clearable="true">
              </el-date-picker>
            </div>
            <el-form label-width="100" color="'#ffffff'" ref="form" :model="formData" :rules="rules">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="applyData.remark" placeholder="请输入备注" max="120" />
              </el-form-item>
            </el-form>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button @click="handleAdd">新增</el-button>
              </el-col>
            </el-row>
            <h3 style="color: black;">资产列表</h3>
            <el-form :model="tableData">
              <vxe-table ref="tableRef" :data="tableData.list" :edit-rules="validRules" keep-source
                :edit-config="{ enabled: true, trigger: 'click', mode: 'row', showStatus: true }">
                <vxe-column type="seq" width="70"></vxe-column>
                <vxe-column field="name" title="名称" :edit-render="{ name: 'VxeInput' }"></vxe-column>
                <vxe-column field="categoryId" title="类别" :edit-render="regionEditRender"></vxe-column>
                <vxe-column field="brand" title="品牌" :edit-render="{ name: 'VxeInput' }"></vxe-column>
                <vxe-column field="model" title="型号" :edit-render="{ name: 'VxeInput' }"></vxe-column>
                <vxe-column title="操作" width="100">
                  <template #default="{ row }">
                    <el-button link @click="handleDelete(row)">删除</el-button>
                  </template>
                </vxe-column>
              </vxe-table>
            </el-form>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="sub">提交</el-button>
          <el-button @click="close">取 消</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import api from "@/api/asset/apply.js";
import { VxeUI } from 'vxe-table';
import useAssetCategoryStore from '@/store/modules/assetCategory';
import treeUtil from '@/utils/tree.js';
import { reactive, ref, onMounted, getCurrentInstance, defineEmits, defineProps, defineExpose } from 'vue';

const proxy = getCurrentInstance();
const assetCategoryStore = useAssetCategoryStore();

const regionEditRender = reactive({
  name: 'VxeTreeSelect',
  options: []
});

async function init() {
  const categoryList = await assetCategoryStore.getList();
  categoryList.forEach(item => {
    item.value = item.id;
    item.label = item.name;
  });
  const treeData = treeUtil.convertToTree(categoryList);
  regionEditRender.options = treeData;
}

const emit = defineEmits(['sub']);
const tableRef = ref();
const rfidBlockRef = ref();

const props = defineProps({
  applyType: {
    type: String,
    required: true,
  }
});

const isEdit = ref(false);
const rules = {
  name: {
    required: true, message: '不能为空'
  }
};

const validRules = ref({
  name: [
    { required: true, message: '必须填写' }
  ]
});

const applyDataInit = {
  id: null,
  applyType: props.applyType,
  remark: null
};

const applyData = reactive(applyDataInit);
const formDataInit = {};
const tableData = reactive({
  loading: false,
  list: [],
});

const openFlag = ref(false);
const form = ref();
const value2 = ref(null);
const pickerOptions = {}; 

const emptyItem = {
  number: null,
  num: 1,
  name: '',
  categoryId: ''
};

const formData = reactive(formDataInit);

function reset() {
  Object.assign(formData, formDataInit);
  tableData.list = [];
}

function open(row) {
  openFlag.value = true;
  reset();
  if (row) {
    api.detail(row).then(response => {
      Object.assign(applyData, response);
      let resFormData = response.formData;
      if (resFormData) {
        if (typeof resFormData === 'string') {
          resFormData = JSON.parse(resFormData);
        }
        Object.assign(formData, resFormData);
      }
      let relItems = formData.items;
      if (!relItems) {
        relItems = [];
      }
      tableData.list = relItems;
    });
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
}

function close() {
  openFlag.value = false;
}

function handleAdd() {
  tableData.list.push({ ...emptyItem });
}

async function handleDelete(row) {
  const $table = tableRef.value;
  if ($table) {
    const type = await VxeUI.modal.confirm('您确定要删除该数据?');
    if (type === 'confirm') {
      const index = tableData.list.findIndex(item => item === row);
      tableData.list.splice(index, 1);
    }
  }
}

function getParams() {
  const apply = { ...applyData };
  apply.applyType = props.applyType;
  formData.items = tableData.list;
  apply.formData = JSON.stringify(formData);
  apply.dateTime = value2.value; 
  return {
    edit: isEdit.value,
    apply: apply
  };
}

async function check() {
  if (!tableData.list.length) {
    VxeUI.modal.message({ status: 'error', content: '入库条目为空，请填写你要入库的条目' });
    return false;
  }
  const $table = tableRef.value;
  const errMap = await $table.validate(true);
  if (errMap) {
    return false;
  }
  return true;
}

/** 保存 */
async function save() {
  let checkResult = await check();
  if (!checkResult) {
    return false;
  }
  api.save(getParams()).then(response => {
    emit("sub");
    close();
  });
}

async function sub() {
  await check();
  api.saveAndSub(getParams()).then(response => {
    emit("sub");
    close();
  });
}

onMounted(() => {
  init();
});

defineExpose({
  open
});
</script>

<style lang="scss">
.dialog-content {
  display: flex;
  width: 100%;
  padding: 10px;

  .dialog-main {
    flex-grow: 1;
    margin-right: 20px;
  }

  .dialog-aside {
    border-left: 1px solid #ccc;
    width: 200px;
  }
}
.el-form-item__label{
  color: #606266df;

}
.block{
margin-bottom: 15px;
  padding: 8px ;
}

</style>